<?php

namespace App\Console\Commands\Test;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;
use App\Notifications\ServiceTelegramNotification;
use Illuminate\Console\Command;
use NotificationChannels\Telegram\TelegramMessage;

class SendNotification extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:send-notification  {message?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */

    /**
     * Chat ID
     *
     * @var mixed
     */
    private $chat_id;

    public function __construct()
    {
        parent::__construct();
        $this->chat_id = config('services.telegram-bot-api.chat_id');
    }

    public function handle(): bool
    {
        $messageText = $this->argument('message');

        if (empty($messageText) || is_null($messageText)) {
            // Если аргумент не передан, формируем сообщение по умолчанию
            $ip = $this->getPublicServerIp();
            $internalIp = $this->getInternalServerIp();
            $hostname = gethostname();
            $commandName = $this->signature;

            $messageText = "This is a test notification from server.\n";
            $messageText .= "Server IP: {$ip}\n";
            $messageText .= "Internal IP: {$internalIp}\n";
            $messageText .= "Hostname: {$hostname}\n";
            $messageText .= "Command: {$commandName}";
        }

        $message = TelegramMessage::create()
            ->to($this->chat_id)
            ->content($messageText);

        try {
            Notification::route('telegram', $this->chat_id)->notify(new ServiceTelegramNotification($message));

            $this->info('Notification sent successfully!');
            return true;
        } catch (\Exception $e) {
            $this->error('Failed to send notification: ' . $e->getMessage());
            return false;
        }
    }

    private function getPublicServerIp(): string
    {
        try {
            $response = Http::get('http://ipinfo.io/ip');
            return trim($response->body());
        } catch (\Exception $e) {
            return 'IP not available';
        }
    }

    private function getInternalServerIp(): string
    {
        if (isset($_SERVER['SERVER_ADDR'])) {
            return $_SERVER['SERVER_ADDR'];
        } else {
            return gethostbyname(gethostname());
        }
    }
}
